package com.xm2.demo.login.user.service;

import com.xm2.demo.login.user.dao.PayRecordsRepository;
import com.xm2.demo.login.user.dao.RecordRepository;
import com.xm2.demo.login.user.dao.UserRepository;
import com.xm2.demo.login.user.vo.OrderDto;
import com.xm2.demo.login.user.vo.RegisterVo;
import com.xm2.demo.login.user.vo.StateDto;
import com.xm2.demo.model.*;
import com.xm2.demo.system.center.dao.CentersRepository;
import com.xm2.demo.system.order.dao.OrderRepository;
import com.xm2.demo.system.order.dao.StateRecordRepository;
import com.xm2.demo.system.order.dao.StateRepository;
import com.xm2.demo.utils.Md5;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Create
 * @create 2018-12-20 15:18
 * @Description：
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository; //用户持久层

    @Autowired
    private RecordRepository recordRepository; //充值记录持久层

    @Autowired
    private CentersRepository centersRepository;    //洗衣中心持久层

    @Autowired
    private OrderRepository orderRepository;    //订单持久层

    @Autowired
    private PayRecordsRepository payRecordsRepository;  //支付记录持久层

    @Autowired
    private StateRecordRepository stateRecordRepository;   //操作状态持久层

    @Autowired
    private StateRepository stateRepository;

    @Override
    public User findUserByUsername(String username) {
        return userRepository.findUserByUsername(username);
    }

    /*
     * description:注册
     * @params [registerVo]
     * @return void
     */
    @Override
    public void save(RegisterVo registerVo) {
        User user = new User();
        registerVo.setPassword(Md5.getMD5(registerVo.getPassword()));
        BeanUtils.copyProperties(registerVo, user);
        user.setPositionId(0);
        userRepository.save(user);
    }

    /*
     * description:修改密码
     * @params [user]
     * @return void
     */
    @Override
    public void updatePassword(User user) {
        userRepository.save(user);
    }

    /*
     * description:充值
     * @params [userId, balance] id ， 余额
     * @return void
     */
    @Transactional
    @Override
    public void rechargeByUserId(Integer userId, Double balance) {
        User user = userRepository.findOne(userId);
        BigDecimal b1 = new BigDecimal(Double.toString(balance));
        BigDecimal b2 = new BigDecimal(Double.toString(user.getBalance()));
        //保留2位小数
        double newBalance = b1.add(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        user.setBalance(newBalance);
        //保存充值记录
        Record record = new Record();
        record.setCustomerId(userId);
        record.setMoney(b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        record.setTime(new Date());
        userRepository.save(user);
        recordRepository.save(record);
    }

    @Override
    public List<String> findCenter(String address) {
        return centersRepository.findAddress(address);
    }

    /*
     * description:保存订单 支付记录 修改用户余额 保存操作状态记录
     * @params [orderDto, payment]支付金额
     * @return void
     */
    @Transactional
    @Override
    public int payOrder(OrderDto orderDto, Double payment,User user1) {
        double newMoney = new BigDecimal(payment).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String orderId = format.format(date);

        //保存预约订单
        Form form = new Form();
        form.setOrderId(orderId);
        form.setMoney(newMoney);
        form.setCustomerName(orderDto.getName());
        form.setStateId(1);
        form.setAddress(orderDto.getAddress()+orderDto.getOrderAddress());
        form.setCenter(orderDto.getCenter());
        form.setFormDate(date);
        form.setSalesmanName("未绑定");
        form.setEvaluation(null);
        form.setShop("未绑定");
        form.setUsername(user1.getUsername());

        User user = userRepository.findUserByName(orderDto.getName());

        //支付记录
        PayRecords payRecords = new PayRecords();
        payRecords.setCustomerId(user.getId());
        payRecords.setMoney(newMoney);
        payRecords.setPayDate(date);

        //保存操作状态记录
        StateRecord stateRecord = new StateRecord();
        stateRecord.setCustomerName(orderDto.getName());
        stateRecord.setOrderId(orderId);
        stateRecord.setFormDate(date);
        stateRecord.setSalesmanName("未绑定");
        stateRecord.setStateId(1);
        stateRecord.setMoney(newMoney);

        //计算余额
        double balance = new BigDecimal(Double.toString(user.getBalance()))
                .subtract(new BigDecimal(Double.toString(payment))).doubleValue();
        if (balance >= 0.0) {
            User newUser = new User();
            BeanUtils.copyProperties(user,newUser);
            newUser.setBalance(balance);

            userRepository.save(newUser);
            payRecordsRepository.save(payRecords);
            orderRepository.save(form);
            stateRecordRepository.save(stateRecord);
            return 1;
        } else {
            return 0;
        }

    }

    /*
     * description:根据订单编号查询状态
     * @params [orderId]
     * @return java.util.List<com.xm2.demo.login.user.vo.StateDto>
     */
    @Override
    public List<StateDto> getStateRecord(String orderId) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<StateRecord> stateRecords = stateRecordRepository.findByOrderId(orderId);
        List<StateDto> stateDtoList = new ArrayList<>();
        for (StateRecord stateRecord : stateRecords) {
            StateDto stateDto = new StateDto();
            stateDto.setStateName(stateRepository
                    .findById(stateRecord.getStateId()).getState());
            stateDto.setFormDate(dateFormat.format(stateRecord.getFormDate()));
            stateDtoList.add(stateDto);
        }

        return stateDtoList;
    }
}
